package com.sky.controller;

import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.GUserInfoDTO;
import com.sky.dto.GUserLoginPasswordDTO;
import com.sky.dto.GUserLoginVerifycodeDTO;
import com.sky.dto.GUserRegiserDTO;
import com.sky.entity.GUser;
import com.sky.exception.EmailException;
import com.sky.properties.JwtProperties;
import com.sky.service.GUserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.GUserLoginVO;
import com.sky.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/guser")
@Slf4j
@Api(tags = "用户信息接口")
public class GUserController {

  @Autowired
  private JwtProperties jwtProperties;

  @Autowired
  private GUserService gUserService;

  private String caculateToken(int guserId) {
    //生成jwt令牌
    Map<String, Object> claims = new HashMap<>();
    claims.put(JwtClaimsConstant.GUer_ID, guserId);
    String token = JwtUtil.createJWT(
        jwtProperties.getGuserSecretKey(),
        jwtProperties.getGuserTtl(),
        claims);
    return token;
  }

  @PostMapping("/login/password")
  @ApiOperation(value = "用户用邮箱密码登录")
  public Result<GUserLoginVO> loginByPassword(
      @RequestBody GUserLoginPasswordDTO gUserLoginPasswordDTO) {
    log.info("用户登录：{}", gUserLoginPasswordDTO);

    GUser gUser = GUser.builder()
        .guserEmail(gUserLoginPasswordDTO.getGuserEmail())
        .guserPassword(gUserLoginPasswordDTO.getGuserPassword())
        .build();

    GUser gUserResult = gUserService.selectUser(gUser);

    String token = caculateToken(gUserResult.getGuserId());

    GUserLoginVO gUserLoginVO = GUserLoginVO.builder()
        .userId(gUserResult.getGuserId())
        .guserName(gUserResult.getGuserName())
        .token(token)
        .build();

    log.info("查询到用户，{}", gUserResult);
    return Result.success(gUserLoginVO);


  }

  @PostMapping("/login/verfiycode")
  @ApiOperation(value = "用户用邮箱验证码登录")
  public Result<GUserLoginVO> loginByVerifycode(
      @RequestBody GUserLoginVerifycodeDTO gUserLoginVerifycodeDTO) {
    if (gUserService.verfiyEmail(gUserLoginVerifycodeDTO.getGuserEmail(),
        gUserLoginVerifycodeDTO.getVerifycode()) == true) {

      GUser gUserResult = gUserService.selectUser(
          GUser.builder().guserEmail(gUserLoginVerifycodeDTO.getGuserEmail()).build());
      String token = caculateToken(gUserResult.getGuserId());
      GUserLoginVO gUserLoginVO = GUserLoginVO.builder()
          .userId(gUserResult.getGuserId())
          .guserName(gUserResult.getGuserName())
          .token(token)
          .build();

      log.info("查询到用户，{}", gUserResult);
      return Result.success(gUserLoginVO);
    } else {
      return Result.error(MessageConstant.EMAIL_VERFIY_CODE_ERROR);
    }

  }

  @PostMapping("/register")
  @ApiOperation(value = "用户注册")
  public Result<GUserLoginVO> registerGUser(@RequestBody GUserRegiserDTO gUserRegiserDTO) {
    if (gUserRegiserDTO.getGuserPassword()==null ||  !gUserRegiserDTO.getGuserPassword() .equals(gUserRegiserDTO.getGuserPasswordTwice()) ) {
      return Result.error(MessageConstant.GUSER_PASSWORD_NOT_SMAE);
    }
    if (gUserService.verfiyEmail(gUserRegiserDTO.getGuserEmail(), gUserRegiserDTO.getVerifycode())
        == true) {
      GUser gUser = GUser.builder()
          .guserEmail(gUserRegiserDTO.getGuserEmail())
          .guserPassword(gUserRegiserDTO.getGuserPassword())
          .build();

      gUserService.insertUser(gUser);
      String token = caculateToken(gUser.getGuserId());
      GUserLoginVO gUserLoginVO = GUserLoginVO.builder()
          .userId(gUser.getGuserId())
          .guserName(gUser.getGuserName())
          .token(token)
          .build();
      return Result.success(gUserLoginVO);
    } else {
      return Result.error(MessageConstant.EMAIL_VERFIY_CODE_ERROR);
    }
  }

  @PostMapping("/resetpassword")
  @ApiOperation(value = "用户修改密码")
  public Result resetPassword(@RequestBody GUserRegiserDTO gUserRegiserDTO){
    if (gUserRegiserDTO.getGuserPassword()==null ||  !gUserRegiserDTO.getGuserPassword() .equals(gUserRegiserDTO.getGuserPasswordTwice()) ) {
      return Result.error(MessageConstant.GUSER_PASSWORD_NOT_SMAE);
    }
    if (gUserService.verfiyEmail(gUserRegiserDTO.getGuserEmail(), gUserRegiserDTO.getVerifycode())
        == true) {
      GUser gUser = GUser.builder()
          .guserEmail(gUserRegiserDTO.getGuserEmail())
          .guserPassword(gUserRegiserDTO.getGuserPassword())
          .build();

      gUserService.updateUserByEmail(gUser);
      return Result.success();
    } else {
      return Result.error(MessageConstant.EMAIL_VERFIY_CODE_ERROR);
    }
  }

  @GetMapping("/info")
  @ApiOperation(value = "获取用户信息")
  public Result<GUser> getGUserInfo(){
    GUser gUser = gUserService.selectUserById();
    gUser.setGuserPassword(null);
    return Result.success(gUser);
  }

  @PostMapping("/changeinfo")
  @ApiOperation(value = "修改用户信息")
  public Result changeGUserInfo(@RequestBody GUserInfoDTO gUserInfoDTO ){
    GUser gUser=GUser.builder()
        .guserId(BaseContext.getCurrentId())
        .guserName(gUserInfoDTO.getGuserName())
        .guserPassword(gUserInfoDTO.getGuserPassword())
        .guserSex(gUserInfoDTO.getGuserSex())
        .guserBirth(gUserInfoDTO.getGuserBirth())
        .build();

    gUserService.updateUserById(gUser);
    return Result.success();
  }


  @PostMapping("/changeemail")
  @ApiOperation(value = "修改用户邮箱")
  public Result changeGUserEmail(String oldEmail,String oldVerifycode,String newEmail,String newVerifycode){
    if (gUserService.verfiyEmail(oldEmail,oldVerifycode )== true &&gUserService.verfiyEmail(newEmail,newVerifycode) ){
      gUserService.updateEmail(oldEmail,newEmail);
    }else{
      throw new EmailException(MessageConstant.EMAIL_VERFIY_CODE_ERROR);
    }
    return Result.success();
  }
}
